import { getLevelFirst, getLevelZero, getLoadMapList, getTenantID, getUserID, requestFunComponFiex } from '@/utils';
import { useRequest } from 'umi';
import { ILoadMapTypeAll } from '@/common';
import { useCallback, useMemo, useState } from 'react';
import { searchCriteriaFun } from '../../Acommon';
import { getBaseUrl } from '@/services/urlconst';

const baseUrl = getBaseUrl();

/**意向公开权限*/
const intentTabSwitch = (curRes: Record<string, any>) => {
  if (curRes?.['/purchaseSourceIntentController/applyCompanyID']) {
    return {
      applyCompanyID: getLevelZero(),
      params: 'applyCompanyID',
      key: 'ManageTabKey',
    };
  } else if (curRes?.['/purchaseSourceIntentController/applyDepartmentID']) {
    return {
      applyDepartmentID: getLevelFirst(),
      params: 'applyDepartmentID',
      key: 'ManageTabKey',
    };
  } else if (curRes?.['/purchaseSourceIntentController/applyerID']) {
    return {
      applyerID: getUserID(),
      params: 'applyerID',
      key: 'ManageTabKey',
    };
  }

  return {};
};

const IntentModalService = (curRes: Record<string, any>) => {
  /***获取数据字典**/
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}`];

  const { loadMapInfo: loadMdicMapList } = getLoadMapList(loadMdicIds);

  /***保存当前的搜索参数**/
  const [manageTableParams, setManageTableParams] = useState<Record<string, any>>({});

  /** 获取权限参数 */
  const CurResList: Record<string, any> = intentTabSwitch(curRes);

  /***管理页获取数据方法**/
  const { tableProps, data, loading, run } = useRequest(
    (reqParams: Record<string, any>) => {
      let PostParams = {
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        ...CurResList,
        ...reqParams,
        state: `${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1005`,
        packFlag: 1,
      };

      /***保存一份参数**/
      setManageTableParams(PostParams);

      const reqbody: Record<string, any> = PostParams;

      const reqUrl = `${baseUrl}/purchaseSourceIntentController/dataGrid/${reqbody?.params}`;

      delete reqbody.key;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, reqbody);
    },
    {
      // manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /***重新请求的方法**/
  const reloadRequest = useCallback((reqParams: any) => {
    reqParams = searchCriteriaFun(reqParams);
    run({ ...reqParams });
  }, []);

  /***页面数据及分页信息**/
  const tableValues = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  /***搜索功能配置columns**/
  const searchList = useMemo(() => {
    return {
      loadMdicMapList,
    };
  }, [loadMdicMapList, manageTableParams]);

  return {
    loading,
    reloadRequest,
    manageTableParams,
    ...tableValues, //页面列表值
    ...searchList,
  };
};

export { IntentModalService, intentTabSwitch };
